from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from collections import OrderedDict
from common.utils.logger import Logger

class StandardResultsSetPagination(PageNumberPagination):
    """
    标准分页器
    """
    # 默认每页显示的数据条数
    page_size = 10
    # URL参数中每页数量的参数名
    page_size_query_param = 'page_size'
    # 每页最大显示数量
    max_page_size = 1000
    # URL参数中页码的参数名
    page_query_param = 'page'

    def paginate_queryset(self, queryset, request, view=None):
        """
        重写分页方法，处理页数超限的情况
        """
        try:
            # 获取当前请求的页码
            page_number = request.query_params.get(self.page_query_param, 1)
            page_number = int(page_number)
            
            # 计算总页数
            paginator = self.django_paginator_class(queryset, self.get_page_size(request))
            total_pages = paginator.num_pages
            
            # 如果请求页数超过最大页数，则显示最后一页
            if page_number > total_pages and total_pages > 0:
                request.query_params._mutable = True
                request.query_params[self.page_query_param] = total_pages
                request.query_params._mutable = False
                
        except Exception as e:
            pass  # 如果发生异常，使用默认页码
            
        return super().paginate_queryset(queryset, request, view)

    def get_paginated_response(self, data):
        """
        重写响应格式
        """
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data),
            ('total_pages', self.page.paginator.num_pages),
            ('current_page', self.page.number),
            ('page_size', self.page_size)
        ]))

class LargeResultsSetPagination(StandardResultsSetPagination):
    """
    大数据量分页器
    """
    page_size = 100
    max_page_size = 5000

class SmallResultsSetPagination(StandardResultsSetPagination):
    """
    小数据量分页器
    """
    page_size = 5
    max_page_size = 100

class CustomPagination(PageNumberPagination):
    """
    自定义分页器
    支持自定义响应格式
    """
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 1000
    page_query_param = 'page'

    def get_page_size(self, request):
        """
        重写获取页面大小的方法
        """
        if self.page_size_query_param:
            try:
                # 优先从 query_params 获取
                page_size = request.query_params.get(self.page_size_query_param)
                if not page_size and request.method in ['POST', 'PUT', 'PATCH']:
                    # 如果是 POST/PUT/PATCH 请求，尝试从 data 获取
                    page_size = request.data.get(self.page_size_query_param)
                
                if page_size:
                    page_size = int(page_size)
                    if page_size > 0:
                        return min(page_size, self.max_page_size)
            except (TypeError, ValueError):
                pass

        return self.page_size

    def paginate_queryset(self, queryset, request, view=None):
        """
        重写分页方法，处理页数超限的情况
        """
        try:
            # 优先从 query_params 获取页码
            page_number = request.query_params.get(self.page_query_param)
            if not page_number and request.method in ['POST', 'PUT', 'PATCH']:
                # 如果是 POST/PUT/PATCH 请求，尝试从 data 获取
                page_number = request.data.get(self.page_query_param)
            
            page_number = int(page_number) if page_number else 1

            # 获取页面大小
            page_size = self.get_page_size(request)
            
            # 计算总页数
            paginator = self.django_paginator_class(queryset, page_size)
            total_pages = paginator.num_pages
            
            # 如果请求页数超过最大页数，则显示最后一页
            if page_number > total_pages and total_pages > 0:
                page_number = total_pages

            # 更新请求参数，确保父类方法能获取到正确的页码
            if hasattr(request.query_params, '_mutable'):
                request.query_params._mutable = True
                request.query_params[self.page_query_param] = str(page_number)
                request.query_params._mutable = False
            
            return super().paginate_queryset(queryset, request, view)
            
        except Exception as e:
            Logger.error(f"Pagination error: {str(e)}")
            return super().paginate_queryset(queryset, request, view)

    def get_paginated_response(self, data):
        """
        自定义响应格式
        """
        return Response({
            'code': 200,
            'message': 'success',
            'data': {
                'list': data,
                'pagination': {
                    'total': self.page.paginator.count,
                    'page_size': self.get_page_size(self.request),  # 使用实际的 page_size
                    'current': self.page.number,
                    'total_pages': self.page.paginator.num_pages,
                    'has_next': self.page.has_next(),
                    'has_previous': self.page.has_previous(),
                }
            }
        })

    def get_paginated_response_schema(self, schema):
        """
        自定义 Swagger 文档中的响应格式
        """
        return {
            'type': 'object',
            'properties': {
                'code': {
                    'type': 'integer',
                    'example': 200
                },
                'message': {
                    'type': 'string',
                    'example': 'success'
                },
                'data': {
                    'type': 'object',
                    'properties': {
                        'list': schema,
                        'pagination': {
                            'type': 'object',
                            'properties': {
                                'total': {
                                    'type': 'integer',
                                    'example': 100
                                },
                                'page_size': {
                                    'type': 'integer',
                                    'example': 10
                                },
                                'current': {
                                    'type': 'integer',
                                    'example': 1
                                },
                                'total_pages': {
                                    'type': 'integer',
                                    'example': 10
                                },
                                'has_next': {
                                    'type': 'boolean',
                                    'example': True
                                },
                                'has_previous': {
                                    'type': 'boolean',
                                    'example': False
                                }
                            }
                        }
                    }
                }
            }
        }

    def get_paginated_data(self, data):
        """
        获取分页数据
        """
        return {
            'list': data,
            'pagination': {
                'total': self.page.paginator.count,
                'page_size': self.get_page_size(self.request),  # 使用实际的 page_size 而不是默认值
                'current': self.page.number,
                'total_pages': self.page.paginator.num_pages,
            }
        }
